<?php
namespace App\Http\Controllers\Business;

use App\Models\WaterMeter;
use App\Models\WaterMeterRadix;
use App\Models\WaterMeterDayConsumption;
use Maatwebsite\Excel\Facades\Excel;
use Log;

class WaterModule {
    //水表列表
    public static function waterMeterList($page=1, $length=50) {
        $skip = ($page - 1) * $length;
        $enterpriseList = WaterMeter::groupby('enterprise_name' )->select('enterprise_name')->get();
        $lists = [];
        foreach($enterpriseList as $enterprise ) {
            $enterpriseName = $enterprise['enterprise_name'];
            $childList =  WaterMeter::where('enterprise_name', $enterpriseName)->orderBy('number')->skip($skip)->take($length)->get();
            $list = [
                'enterprise_name' => $enterpriseName,
                'child_lists' => $childList
            ];
            array_push($lists, $list);
        }
        $data = [
            'count' => count($enterpriseList),
            'lists' => $lists
        ];
        return ['status'=>'success', 'data'=> $data];
    }
    //新增水表
    public static function addWaterMeter($number, $name, $enterpriseName, $caliber, $accuracyClass, $radix, $rate, $area, $latitude, $longitude, $lastTime, $period, $fatherNode) {
        if(!$number || !$name) {
            return ['status'=>'failed', 'message'=> '请输入名称和编号'];
        }
        if(!strcmp($fatherNode, 0)) {
            $nodeLevel = 1;
            $isFather = 1;
        } else {
            $fatherNodeLevel = WaterMeter::where('number', $fatherNode)->pluck('node_level')->first();
            if(!$fatherNodeLevel) {
                return ['status'=>'failed', 'message'=>'父节点是错误的'];
            }
            $nodeLevel = $fatherNodeLevel + 1;
            if(WaterMeter::where('father_node', $fatherNode)->first()) {
                $isFather = 1;
            } else {
                $isFather = 0;
            }
        }
        $waterMeter = WaterMeter::create([
            'number' => $number,
            'name' => $name,
            'enterprise_name' => $enterpriseName,
            'caliber' => $caliber,
            'accuracy_class' => $accuracyClass,
            'radix' => $radix,
            'rate' => $rate,
            'area' => $area,
            'latitude' => $latitude,
            'longitude' => $longitude,
            'last_time' => $lastTime,
            'last_radix' => $radix,
            'period' => $period,
            'father_node' => $fatherNode,
            'is_father' => $isFather,
            'node_level' => $nodeLevel,
            'status' => 1,
        ]);
        self::addWaterMeterRadix($number, $radix);
        return ['status'=>'success', 'message'=>'新增成功'];
    }
    //获取水表详情
    public static function getWaterMeter($id) {
        if(!$id) {
            return ['status'=>'failed', 'message'=>'参数不对'];
        }
        $data = WaterMeter::where('id', $id)->first();
        return ['status'=>'success', 'data'=>$data];
    }
    //编辑水表
    public static function editWaterMeter($id, $name, $enterpriseName, $caliber, $accuracyClass, $radix, $rate, $area, $latitude, $longitude, $fatherNode) {
        if(!$id || !$name) {
            return ['status'=>'failed', 'message'=>'参数不对'];
        }
        $waterMeter = WaterMeter::where('id', $id)->first();
        if(!$waterMeter) {
            return ['status'=>'failed', 'message'=>'获取信息失败'];
        }
        if(!strcmp($fatherNode, 0)) {
            $nodeLevel = 1;
            $isFather = 1;
        } else {
            $fatherNodeLevel = WaterMeter::where('number', $fatherNode)->pluck('node_level')->first();
            if(!$fatherNodeLevel) {
                return ['status'=>'failed', 'message'=>'父节点是错误的'];
            }
            if(WaterMeter::where('father_node', $fatherNode)->first()) {
                $isFather = 1;
            } else {
                $isFather = 0;
            }
            $nodeLevel = $fatherNodeLevel + 1;
        }
        if($waterMeter->radix != $radix) {
            self::addWaterMeterRadix($waterMeter->number, $radix);
            $waterMeter->consumption = $radix - $waterMeter->radix;
            $waterMeter->last_radix = $waterMeter->radix;
            $waterMeter->radix = $radix;
            $waterMeter->period = ceil((time() - strtotime($waterMeter->updated_at)) / 86400);
            $waterMeter->last_time = date('Y-m-d H:i:s', strtotime($waterMeter->updated_at));
        }
        $waterMeter->name = $name;
        $waterMeter->enterprise_name = $enterpriseName;
        $waterMeter->accuracy_class = $accuracyClass;
        $waterMeter->caliber = $caliber;
        $waterMeter->rate = $rate;
        $waterMeter->area = $area;
        $waterMeter->latitude = $latitude;
        $waterMeter->longitude = $longitude;
        $waterMeter->father_node = $fatherNode;
        $waterMeter->is_father = $isFather;
        $waterMeter->node_level = $nodeLevel;
        $waterMeter->save();
        return ['status'=>'success', 'message'=>'修改成功'];
    }
    //编辑水表底数
    public static function editWaterMeterRadix($number, $name,  $radix, $created_at) {
        if(!$number || !$name || !$radix || !$created_at) {
            return ['status'=>'failed', 'message'=>'参数错误'];
        }
        $waterMeter = WaterMeter::where('name', $name)->where('number', $number)->first();
        if($waterMeter) {
            $lastRadix = $waterMeter->radix;
            $lastTime = $waterMeter->updated_at; 
            $waterMeterRadix = WaterMeterRadix::create([
                    'number' => $number,
                    'radix' => $radix,
                    'status' => 1,
                    'user_id' => 1,
                    'created_at' => $created_at,
                    'updated_at' => $created_at
                ]);
            $waterMeter->last_radix = $lastRadix;
            $waterMeter->last_time = $lastTime;
            $waterMeter->radix = $radix;
            $waterMeter->save();
            return ['status'=>'success', 'message'=>'修改成功'];
        } else {
            return ['status'=>'failed', 'message'=>'修改失败'];
        }
    }
    //编辑水表状态
    public static function editWaterMeterStatus($number, $name, $status, $check_time) {
        if(!$number || !$name || !$check_time) {
            return ['status'=>'failed', 'message'=>'参数错误'];
        }
        $waterMeter = WaterMeter::where('name', $name)->where('number', $number)->first();
        if($waterMeter) {
            $waterMeter->status = $status;
            $waterMeter->check_time = $check_time;
            $waterMeter->save();
            return ['status'=>'success', 'message'=>'修改成功'];
        } else {
            return ['status'=>'failed', 'message'=>'修改失败'];
        }
    }
    //写入水表底数表
    public static function addWaterMeterRadix($number, $radix, $created_at=null, $updated_at=null) {
        if(!$number || !$radix || $radix==0) {
            return ['status'=>'failed', 'message'=>'参数错误'];
        }
        if($created_at != null) {
            $waterMeterRadix = WaterMeterRadix::create([
                'number' => $number,
                'radix' => $radix,
                'status' => 1,
                'user_id' => 1,
                'created_at' => $created_at,
                'updated_at' => $updated_at
            ]);
        } else {
            $waterMeterRadix = WaterMeterRadix::create([
                'number' => $number,
                'radix' => $radix,
                'status' => 1,
                'user_id' => 1,
                'craeted_at' =>  date('Y-m-d H:i:s'),
                'updated_at' => date('Y-m-d H:i:s')
            ]);
        }
        return ['status'=>'success', 'message'=>'新增成功'];
    }
    //获取经纬度
    public static function getLongitudeAndLatitude($id) {
        if(!$id) {
            return ['status'=>'failed', 'message'=>'参数不对'];
        }
        $data = WaterMeter::where('id', $id)->select('longitude', 'latitude')->first();
        return ['status'=>'success', 'data'=> $data];
    }
    //获取父节点
    public static function getFatherNode($id) {
        if(!$id) {
            return ['status'=>'failed', 'message'=>'参数不对'];
        }
        $fatherNode = WaterMeter::where('id', $id)->pluck('father_node')->first();
        if(!strcmp($fatherNode, 0)) {
            $fatherNode = WaterMeter::where('id', $id)->pluck('number')->first();
        }
        $data = WaterMeter::where('number', $fatherNode)->select('id', 'name', 'number','consumption', 'rate', 'radix', 'area', 'longitude', 'latitude', 'period', 'node_level')->first();
        if(!$data) {
            return ['status'=>'failed', 'message'=>'获取父节点失败'];
        }
        return ['status'=>'success', 'data'=>$data];
    }
    //获取子节点
    public static function getChildNode($id) {
        if(!$id) {
            return ['status'=>'failed', 'message'=>'参数不对'];
        }
        $data = WaterMeter::where('id', $id)->select('id', 'name', 'number', 'rate','consumption', 'radix', 'area', 'longitude', 'latitude', 'period', 'node_level')->first();
        if(!$data) {
            return ['status'=>'failed', 'message'=>'获取信息失败'];
        }
        return ['status'=>'success', 'data'=>$data];
    }
    //子节点列表
    public static function childList($number) {
        if(!$number) {
            return ['status'=>'failed', 'message'=>'参数错误'];
        }
        $data = WaterMeter::where('father_node', $number)->select('id', 'name', 'number', 'radix', 'last_radix','last_time','updated_at','rate','consumption', 'area', 'longitude', 'latitude', 'period', 'node_level')->get();
        return ['status'=>'success', 'data'=>$data];
    }
    //线路图
    public static function getWaterLine() {

    }
    //肿瘤医院树状结构
    public static function cancerHospitalTree() {
        $fatherNode = 'ch00';
        $basisInfo = WaterMeter::where('number', $fatherNode)->select('id', 'number','name', 'area', 'node_level')->first();
        //TODO 只能下放到第三级
        $firstClassNodeList = WaterMeter::where('father_node', $fatherNode)->select('id', 'number','name', 'area', 'is_father', 'node_level', 'father_node')->get();
        foreach ($firstClassNodeList as $v =>$k) {
            $secondClassNodeList = [];
            if($firstClassNodeList[$v]['is_father']) {
                $secondClassNodeList = WaterMeter::where('father_node', $firstClassNodeList[$v]['number'])->select('id', 'number','name', 'area', 'is_father', 'node_level', 'father_node')->get();
            }
            $firstClassNodeList[$v]['second_class_node_list'] = $secondClassNodeList;
        }
        $data = [
            'base_info' => $basisInfo,
            'child_list' => $firstClassNodeList
        ];
        return ['status'=>'success', 'data'=>$data];
    }
    //一级水表列表
    public static function firstNodeLevelWaterMeterList() {
        $lists = WaterMeter::where('node_level', 1)->select('number', 'enterprise_name','name', 'id', 'longitude', 'latitude', 'consumption')->get();
        return ['status'=>'success', 'data'=>$lists];
    }
    //excel导入水表底数
    public static function importWaterMeterRadixExcel($filePath) {
        //$filePath = 'storage/excel/test.xlsx';
        Excel::load($filePath, function($reader) {
            $data = $reader->all();
            foreach($data as $sheetList) {
                $sheetTitle = $sheetList->getTitle();
                $items = $sheetList->toArray();
                foreach($items as $item) {
                    $time = current($item);
                    $time = date('Y-m-d H:i', strtotime($time));
                    $radix = next($item);
                    if($radix) {
                        self::addWaterMeterRadix($sheetTitle, $radix, $time, $time);
                    }
                }
            }
        });
        return ['status'=>'success', 'message'=>'revise success'];
    }
    //获取单个水表底数列表
    public static function singleWaterMeterRadixList($id, $page=1, $length=20) {
        if(!$id) {
            return ['status'=>'failed', 'message'=>'参数错误'];
        }
        $number = WaterMeter::where('id', $id)->pluck('number')->first();
        if(!$number) {
            return ['status'=>'failed', 'message'=>'获取信息失败'];
        }
        $total = WaterMeterRadix::where('number', $number)->count();
        $skip = ($page-1)* $length;
        $lastPage = ceil($total / $length);
        $lists = WaterMeterRadix::where('number', $number)->orderBy('created_at', 'asc')->skip($skip)->take($length)->get();
        $data = [
            'total' => $total,
            'page' => $page,
            'length' => $length,
            'last_page' => $lastPage,
            'lists' => $lists
        ];
        return ['status'=>'success', 'data'=>$data];

    }
    //获取指定日期的单个水表底数列表
    public static function singleWaterMeterRadixListByDay($id, $day) {
        if(!$id) {
            return ['status'=>'failed', 'message'=>'参数错误'];
        }
        $number = WaterMeter::where('id', $id)->pluck('number')->first();
        if(!$number) {
            return ['status'=>'failed', 'message'=>'获取信息失败'];
        }
        $startTime = date('Y-m-d H:i:s', strtotime($day . " 00:00:00") - 3*60);
        $lastTime = date('Y-m-d H:i:s', strtotime($day . " 00:00:00") + 60*60*24 - 3*60);
        $lists = WaterMeterRadix::where('number', $number)->where('created_at', '>=', $startTime)->where('created_at', '<=',$lastTime)
            ->orderBy('created_at', 'asc')->get();
        $labels = [];
        $radixChartData = [];
        foreach ($lists as $list) {
            array_push($labels, date('H:i',strtotime($list['created_at'])));
            array_push($radixChartData, $list['radix']);
        }
        $data = [
            'lists' => $lists,
            'labels' => $labels,
            'radix_chart_data' => $radixChartData
        ];
        return ['status'=>'success', 'data'=>$data];
    }
    //每周水表和上周数据比较
    public static function waterMeterWeekComparison($id) {
        if(!$id) {
            return ['status'=>'failed', 'message'=>'参数错误'];
        }
        $weekDay = date('w');
        if($weekDay == "1") {
            $labels = ["周二", "周三", "周四", "周五", "周六", "周日","周一"];
        } elseif($weekDay == "2") {
            $labels = [ "周三", "周四", "周五", "周六", "周日","周一","周二"];
        } elseif($weekDay == "3") {
            $labels = [ "周四", "周五", "周六", "周日","周一","周二", "周三"];
        } elseif($weekDay == "4") {
            $labels = ["周五", "周六", "周日","周一","周二", "周三", "周四"];
        } elseif($weekDay == "5") {
            $labels = [ "周六", "周日","周一","周二", "周三", "周四", "周五"];
        } elseif($weekDay == "6") {
            $labels = ["周日","周一","周二", "周三", "周四", "周五", "周六"];
        } elseif($weekDay == "7") {
            $labels = ["周一","周二", "周三", "周四", "周五", "周六", "周日"];
        } else {
            return ['status'=>'failed', 'message'=>'获取日期错误'];
        }
        $number = WaterMeter::where('id', $id)->pluck('number')->first();
        if(!$number) {
            return ['status'=>'failed', 'message'=>'获取信息失败'];
        }
        $thisWeekData = [
            self::getSingleWaterMeterConsumptionByNumberAndDate($number, date('Y-m-d', strtotime('-6days'))),
            self::getSingleWaterMeterConsumptionByNumberAndDate($number, date('Y-m-d', strtotime('-5days'))),
            self::getSingleWaterMeterConsumptionByNumberAndDate($number, date('Y-m-d', strtotime('-4days'))),
            self::getSingleWaterMeterConsumptionByNumberAndDate($number, date('Y-m-d', strtotime('-3days'))),
            self::getSingleWaterMeterConsumptionByNumberAndDate($number, date('Y-m-d', strtotime('-2days'))),
            self::getSingleWaterMeterConsumptionByNumberAndDate($number, date('Y-m-d', strtotime('-1days'))),
            self::getSingleWaterMeterConsumptionByNumberAndDate($number, date('Y-m-d'))
        ];
        $lastWeekData = [
            self::getSingleWaterMeterConsumptionByNumberAndDate($number, date('Y-m-d', strtotime('-13days'))),
            self::getSingleWaterMeterConsumptionByNumberAndDate($number, date('Y-m-d', strtotime('-12days'))),
            self::getSingleWaterMeterConsumptionByNumberAndDate($number, date('Y-m-d', strtotime('-11days'))),
            self::getSingleWaterMeterConsumptionByNumberAndDate($number, date('Y-m-d', strtotime('-10days'))),
            self::getSingleWaterMeterConsumptionByNumberAndDate($number, date('Y-m-d', strtotime('-9days'))),
            self::getSingleWaterMeterConsumptionByNumberAndDate($number, date('Y-m-d', strtotime('-8days'))),
            self::getSingleWaterMeterConsumptionByNumberAndDate($number, date('Y-m-d', strtotime('-7days')))
        ];
        $data = [
            'labels' => $labels,
            'this_week_data' => $thisWeekData,
            'last_week_data' => $lastWeekData
        ];
        return ['status'=>'success', 'data'=>$data];
    }
    //获取水表某一天的用水量
    public static function getSingleWaterMeterConsumptionByNumberAndDate($number, $date) {
        if(!$number || !$date) {
            return 0;
        }
        $consumption = WaterMeterDayConsumption::where('number', $number)->where('current_date', $date)->pluck('consumption')->first();
        return ($consumption == '') ? 0: $consumption;
    }
    //每日数据
    public static function waterMeterDayConsumptionList($id, $page=1, $length=30) {
        if(!$id) {
            return ['status'=>'failed', 'message'=>'参数错误'];
        }
        $number = WaterMeter::where('id', $id)->pluck('number')->first();
        if(!$number) {
            return ['status'=>'failed', 'message'=>'无数据'];
        }
        $total = WaterMeterDayConsumption::where('number', $number)->count();
        $skip = ($page - 1) * $length;
        $lists = WaterMeterDayConsumption::where('number', $number)->orderBy('current_date')->skip($skip)->take($length)->select('number','consumption', 'current_date')->get();
        $lastPage = ceil($total/$length);
        $labels = [];
        $consumptionChartData = [];
        foreach ($lists as $list) {
            array_push($labels, $list['current_date']);
            array_push($consumptionChartData, $list['consumption']);
        }
        $data = [
            'total' => $total,
            'page' => $page,
            'length' => $length,
            'last_page' => $lastPage,
            'lists' => $lists,
            'labels' => $labels,
            'consumption_chart_data' => $consumptionChartData
        ];
        return ['status'=>'success', 'data'=>$data];
    }
    //写入watermeter_day_consumption
    public static function insertIntoWaterMeterDayConsumption($number, $consumption, $current_date) {
        if(!$number || !$consumption || !$current_date) {
            return ['status'=>'failed', 'message'=>'参数错误'];
        }
        if(WaterMeterDayConsumption::where('number', $number)->where('current_date', $current_date)->first()) {
            return ['status'=>'failed', 'message'=>'已经写入过这条记录'];
        }
        $waterMeterDayConsumption = WaterMeterDayConsumption::create([
            'number' => $number,
            'consumption' => $consumption,
            'current_date' => $current_date
        ]);
        $waterMeterDayConsumption->save();
        return ['status'=>'success', 'message'=>'新增成功'];
    }
    //自动化任务
    public static function autoInsertIntoWaterMeterDayConsumption($today) {
        //$today  = date('Y-m-d') . " 00:00:00";
        //$today = "2018-03-07 00:00:00";
        $startTime = date('Y-m-d H:i:s',strtotime($today) - 2 * 60);  //23:58
        $lastTime = date('Y-m-d H:i:s', strtotime($today) + 60*60*24 - 2*60);
        $numberList = WaterMeterRadix::where('created_at', '>=', $startTime)->where('created_at', '<=', $lastTime)->groupby('number')->select('number')->get();
        foreach($numberList as $list) {
            $number = $list['number'];
            if(WaterMeterDayConsumption::where('number', $number)->where('current_date', $today)->first()) {
                continue;
            }
            $maxRadix = WaterMeterRadix::where('number', $number)->where('created_at', '>=', $startTime)->where('created_at', '<=', $lastTime)->max('radix');
            $minRadix = WaterMeterRadix::where('number', $number)->where('created_at', '>=', $startTime)->where('created_at', '<=', $lastTime)->min('radix');
            $consumption = bcsub($maxRadix, $minRadix,2);
            $waterMeterDayConsumption = WaterMeterDayConsumption::create([
                'number' => $number,
                'consumption' => $consumption,
                'current_date' => $today,
            ]);
            $waterMeterDayConsumption->save();
        }
        return ['status'=>'success', 'message'=>'写入成功'];

    }

}

?>
